package com.iamteer.cupband;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Fragment;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

public class ObserveFragment extends Fragment implements View.OnClickListener {

    private ImageView ivDateBefore;
    private ImageView ivDateAfter;
    private ImageView ivDecrease;
    private ImageView ivIncrease;
    private ImageView ivResultBackground;

    private TextView tvDate;
    private TextView tvResult;
    private TextView tvGoal;
    private TextView tvResultProgressBar;

    private ProgressBar pbResult;

    private Button btnRemoteInteract;
    private Button btnSetGoal;
    private Button btnBonding;

//    private static int Goal;
    private static int position;

    private int ScreenWidth;
    private int ScreenDpi;

    private FrameLayout resultFrameLayout;

    public Date CurrentDate;
    public Calendar CurrentCalendar;
    public final static String WeekDayString[] = {"日", "一", "二", "三", "四", "五", "六"};

    private ComputeAngle computeAngle = new ComputeAngle();

    public ObserveFragment() {
        // Required empty public constructor
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Log.i("TAG", "ObserveFragment CreateView");
        View root = inflater.inflate(R.layout.fragment_observe, container, false);


        FindViews(root);
        InitiateDate();
        InitiateProgressBar();

        tvDate.setOnClickListener(this);
        ivDecrease.setOnClickListener(this);
        ivIncrease.setOnClickListener(this);
        ivDateAfter.setOnClickListener(this);
        ivDateBefore.setOnClickListener(this);

        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                MainActivity.mainActivity.runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        //更新UI
                        if (MainActivity.result > MainActivity.resultBack) {
                            System.out.println(String.format("Old: %d, new: %d", MainActivity.resultBack, MainActivity.result));
//                            ResultIncrease();
                            UpDateResult();
                            MainActivity.resultBack = MainActivity.result;
                        }
                    }
                });
            }
        },1000, 100);

        LocalBroadcastManager.getInstance(MainActivity.mainActivity).registerReceiver(UARTStatusChangeReceiver, makeGattUpdateIntentFilter());



//        new Thread() {
//            public void run() {
//                //这儿是耗时操作，完成之后更新UI；
//                getActivity().runOnUiThread(new Runnable() {
//
//                    @Override
//                    public void run() {
//                        //更新UI
//                        if (MainActivity.Result > MainActivity.ResultBack ){
//                            ResultIncrease();
//                            MainActivity.resultBack = MainActivity.result;
//                            System.out.println(String.format("Old: %d, new: %d", MainActivity.resultBack, MainActivity.result));
//                        }
//                    }
//
//                });
//            }
//        }.start();

        return root;
    }

    @Override
    public void onResume() {
        super.onResume();

        InitiateProgressBar();
    }

    public static void setMargins(View view, int left, int top, int right, int bottom) {
        if (view.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
            ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) view.getLayoutParams();
            p.setMargins(left, top, right, bottom);
            view.requestLayout();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ivDateBefore:
                DateBefore();
                break;

            case R.id.ivDateAfter:
                DateAfter();
                //MainActivity.result++;
                break;

            case R.id.ivDecrease:
//                    ResultDecrease();
                MainActivity.result--;
                UpDateResult();
                break;

            case R.id.ivIncrease:
                MainActivity.result++;
                UpDateResult();
//                    ResultIncrease();
                break;

            case R.id.tvDate:
                Date date = new Date();
                DatePickerDialog datePickerDialog = new DatePickerDialog(getActivity(), new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                        System.out.println(String.format("%d-%d-%d", year, monthOfYear, dayOfMonth));
                        DateSet(year, monthOfYear, dayOfMonth);
                    }
                }, 1900+date.getYear(), date.getMonth(), date.getDate());
                datePickerDialog.show();
                break;

        }
    }



    private void FindViews(View root) {
        ivDateBefore = (ImageView) root.findViewById(R.id.ivDateBefore);
        ivDateAfter = (ImageView) root.findViewById(R.id.ivDateAfter);
        ivDecrease = (ImageView) root.findViewById(R.id.ivDecrease);
        ivIncrease = (ImageView) root.findViewById(R.id.ivIncrease);
        ivResultBackground = (ImageView) root.findViewById(R.id.ivResultBackground);

        tvDate = (TextView) root.findViewById(R.id.tvDate);
        tvResult = (TextView) root.findViewById(R.id.tvResult);
        tvGoal = (TextView) root.findViewById(R.id.tvGoal);
        tvResultProgressBar = (TextView) root.findViewById(R.id.tvResultProgressBar);

        pbResult = (ProgressBar) root.findViewById(R.id.pbResult);

        btnRemoteInteract = (Button) root.findViewById(R.id.btnRemoteInteract);
        btnSetGoal = (Button) root.findViewById(R.id.btnSetGoal);
        btnBonding = (Button) root.findViewById(R.id.btnBonding);

        resultFrameLayout = (FrameLayout) root.findViewById(R.id.resultFrameLayout);
    }

    public void ResultIncrease() {
        int position;

        MainActivity.result++;
        if(MainActivity.result <= MainActivity.Goal) {
            pbResult.setProgress(MainActivity.result);
            position = (ScreenWidth - 56*ScreenDpi/160) / MainActivity.Goal * MainActivity.result;
            setMargins(resultFrameLayout, position, 0, 0, 0);
        }

        tvResultProgressBar.setText(Integer.toString(MainActivity.result));
        tvResult.setText(Integer.toString(MainActivity.result));
        SharedPreferences sp = getActivity().getSharedPreferences(MainActivity.SharedPreferencesName, Activity.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putInt(MainActivity.KEY_result, MainActivity.result);
        editor.apply();

        System.out.println("ResultIncrease: " + MainActivity.result);
    }

    private void ResultDecrease() {
        int position;
        MainActivity.result--;
        if (MainActivity.result < 0) {
            MainActivity.result = 0;
        }
        if(MainActivity.result <= MainActivity.Goal) {
            pbResult.setProgress(MainActivity.result);
            position = (ScreenWidth - 56*ScreenDpi/160) / MainActivity.Goal * MainActivity.result;
            setMargins(resultFrameLayout, position, 0, 0, 0);
//                System.out.println("Position: " + position);
        }
        tvResultProgressBar.setText(Integer.toString(MainActivity.result));
        tvResult.setText(Integer.toString(MainActivity.result));

        SharedPreferences sp = getActivity().getSharedPreferences(MainActivity.SharedPreferencesName, Activity.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putInt(MainActivity.KEY_result, MainActivity.result);
        editor.apply();
        System.out.println("ResultDecrease: " + MainActivity.result);
    }

    private void UpDateResult(){
        if (MainActivity.result < 0) {
            MainActivity.result = 0;
        }
        if(MainActivity.result <= MainActivity.Goal) {
            pbResult.setProgress(MainActivity.result);
            position = (ScreenWidth - 56*ScreenDpi/160) / MainActivity.Goal * MainActivity.result;
            setMargins(resultFrameLayout, position, 0, 0, 0);
        }
        tvResultProgressBar.setText(Integer.toString(MainActivity.result));
        tvResult.setText(Integer.toString(MainActivity.result));

        SharedPreferences sp = getActivity().getSharedPreferences(MainActivity.SharedPreferencesName, Activity.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putInt(MainActivity.KEY_result, MainActivity.result);
        editor.apply();
        System.out.println("Result: " + MainActivity.result);
    }
    private void InitiateProgressBar() {

        int position;

        DisplayMetrics dm = getResources().getDisplayMetrics();
        ScreenWidth = dm.widthPixels;
        ScreenDpi   = dm.densityDpi;

        tvResult.setText(Integer.toString(MainActivity.result));
        tvGoal.setText("/" + Integer.toString(MainActivity.Goal));
        pbResult.setMax(MainActivity.Goal);

        pbResult.setProgress(MainActivity.result);

        position = (ScreenWidth - 168) / MainActivity.Goal * MainActivity.result;
        setMargins(resultFrameLayout, position, 0, 0, 0);
        tvResultProgressBar.setText(Integer.toString(MainActivity.result));
    }

    private void InitiateDate() {
        int month, day, weekday;
        CurrentCalendar = Calendar.getInstance(Locale.CHINA);
        CurrentDate = new Date();
        CurrentCalendar.setTime(CurrentDate);

        month = CurrentCalendar.get(Calendar.MONTH) + 1;
        day = CurrentCalendar.get(Calendar.DAY_OF_MONTH);
        weekday = CurrentCalendar.get(Calendar.DAY_OF_WEEK);

//        tvDate.setText(month + "月" + day + "日 星期" + WeekDayString[weekday - 1]);
        tvDate.setText(String.format("%02d月%02d日 星期", month, day)+ WeekDayString[weekday]);
    }

    private void DateBefore() {
        int month, date, day;
        CurrentCalendar.add(Calendar.DAY_OF_YEAR, -1);
        CurrentDate = CurrentCalendar.getTime();
        month = CurrentDate.getMonth() + 1;
        date = CurrentDate.getDate();
        day = CurrentDate.getDay();
//        tvDate.setText(month + "月" + date + "日 星期" + WeekDayString[day]);
        tvDate.setText(String.format("%02d月%02d日 星期", month, date)+ WeekDayString[day]);
    }

    private void DateAfter() {
        int month, date, day;
        CurrentCalendar.add(Calendar.DAY_OF_YEAR, 1);
        CurrentDate = CurrentCalendar.getTime();
        month = CurrentDate.getMonth() + 1;
        date = CurrentDate.getDate();
        day = CurrentDate.getDay();
//        tvDate.setText(month + "月" + date + "日 星期" + WeekDayString[day]);
        tvDate.setText(String.format("%02d月%02d日 星期", month, date)+ WeekDayString[day]);
    }

    private void DateSet(int year, int monthOfYear, int dayOfMonth){
        int day;
        CurrentCalendar.set(year, monthOfYear, dayOfMonth);
        day = CurrentCalendar.get(Calendar.DAY_OF_WEEK);
//        tvDate.setText(Integer.toString(monthOfYear+1) + "月" + dayOfMonth + "日 星期" + WeekDayString[day]);
        tvDate.setText(String.format("%02d月%02d日 星期", monthOfYear+1, dayOfMonth)+ WeekDayString[day]);
    }


    private final BroadcastReceiver UARTStatusChangeReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            //*********************//
            if (action.equals(UartService.ACTION_GATT_CONNECTED)) {
                MainActivity.mState = MainActivity.UART_PROFILE_CONNECTED;
                Log.d(MainActivity.TAG, "UART_CONNECT_MSG");
            }

            //*********************//
            if (action.equals(UartService.ACTION_GATT_DISCONNECTED)) {
                MainActivity.mState = MainActivity.UART_PROFILE_DISCONNECTED;
                MainActivity.mService.close();

            }

            //*********************//
            if (action.equals(UartService.ACTION_GATT_SERVICES_DISCOVERED)) {
                MainActivity.mService.enableTXNotification();
            }
            //*********************//
            if (action.equals(UartService.ACTION_DATA_AVAILABLE)) {
                ProcessData(intent);
            }
            //*********************//
            if (action.equals(UartService.DEVICE_DOES_NOT_SUPPORT_UART)) {
                Toast.makeText(getActivity(), "Device doesn't support UART. Disconnecting", Toast.LENGTH_SHORT).show();
                MainActivity.mService.disconnect();
            }
        }
    };



    private static IntentFilter makeGattUpdateIntentFilter() {
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(UartService.ACTION_GATT_CONNECTED);
        intentFilter.addAction(UartService.ACTION_GATT_DISCONNECTED);
        intentFilter.addAction(UartService.ACTION_GATT_SERVICES_DISCOVERED);
        intentFilter.addAction(UartService.ACTION_DATA_AVAILABLE);
        intentFilter.addAction(UartService.DEVICE_DOES_NOT_SUPPORT_UART);
        return intentFilter;
    }

    private void ProcessData(Intent intent){
        final String rxStr = computeAngle.setRawData(intent.getByteArrayExtra(UartService.EXTRA_DATA));
        final short x, y, z;
//        final float xf, yf, zf;
        final double waterlevel;
        x = computeAngle.getAcceleration().x;
        y = computeAngle.getAcceleration().y;
        z = computeAngle.getAcceleration().z;

//        xf = x/256f;
//        yf = y/256f;
//        zf = z/256f;

        waterlevel = -y / Math.sqrt(y*y + z*z);
        MainActivity.waterLeft = (int) ( 100 * waterlevel );

        System.out.println(String.format("Water Left: %f   %d%%    %s", waterlevel, MainActivity.waterLeft, rxStr));

        if(MainActivity.waterLeft <= 0  && computeAngle.getLastLevel() > 0){
            MainActivity.result++;
            System.out.println("杯数：" + MainActivity.result);
            getActivity().runOnUiThread(new Runnable() {
                public void run() {
                    UpDateResult();
                }
            });
        }
    }
}
